﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StyleMVVM.Data.Collections
{
	public class ConcurrentBag<T> : ICollection, IEnumerable<T>
	{
		protected object lockObject = new object();
		protected List<T> internalList = new List<T>();

		IEnumerator<T> IEnumerable<T>.GetEnumerator()
		{
			lock (lockObject)
			{
				return new List<T>(internalList).GetEnumerator();
			}
		}

		public IEnumerator GetEnumerator()
		{
			lock (lockObject)
			{
				return new List<T>(internalList).GetEnumerator();
			}
		}

		public void Add(T value)
		{
			lock (lockObject)
			{
				internalList.Add(value);
			}
		}

		public void CopyTo(Array array, int index)
		{
			throw new NotImplementedException();
		}

		public int Count
		{
			get
			{
				lock (lockObject)
				{
					return internalList.Count;
				}
			}
		}

		public bool IsSynchronized { get; private set; }

		public object SyncRoot { get; private set; }

		public bool TryTake(out T outValue)
		{
			lock (lockObject)
			{
				if (internalList.Count > 0)
				{
					outValue = internalList[0];

					internalList.RemoveAt(0);

					return true;
				}
			}

			outValue = default(T);

			return false;
		}
	}
}